
import { _decorator, Component, Node ,TiledMap ,EventHandler ,resources ,SpriteFrame ,Sprite ,Button ,TiledLayer
    ,UITransform ,find ,log} from 'cc';
import {MapUtil} from "./mapUtil";
import {ClientEvent} from "../framework/clientEvent";
import {Constant} from "../framework/constant";
import {LogicManager} from "./logicManager";
import {DisplayManager} from "./displayManager";
import {Player} from "./GameState";
const { ccclass, property } = _decorator;

/**
 * Predefined variables
 * Name = MapLogic
 * DateTime = Mon Dec 20 2021 17:22:07 GMT+0800 (中国标准时间)
 * Author = yly1234560
 * FileBasename = mapLogic.ts
 * FileBasenameNoExtension = mapLogic
 * URL = db://assets/scripts/core/mapLogic.ts
 * ManualUrl = https://docs.cocos.com/creator/3.3/manual/zh/
 *
 */
 
@ccclass('MapLogic')
export class MapLogic extends Component {

    @property({type:TiledMap})
    private tiledMap = null!;

    private _parent: DisplayManager = null!;

    onEnable() {
        ClientEvent.on(Constant.EVENT_MAP.INIT_PIECES, this._initPieces, this);
    }

    onDisable() {
        ClientEvent.off(Constant.EVENT_MAP.INIT_PIECES, this._initPieces, this);
    }

    start () {
        MapUtil.instance.init(this.tiledMap.getTileSize().height,this.tiledMap.getMapSize().width,this.tiledMap.getMapSize().height);
        // 初始化 方法 添加 脚印精灵
        // this.initFootPrint();
        // 初始化所有棋子
        // this._initPieces();
        // 初始化兽穴、陷阱、河道
        this.initBlock();


        let node = find("Canvas/display") as Node;
        this._parent = node.getComponent(DisplayManager);
    }

    private _initPieces() {
        let pieces = this.tiledMap.getObjectGroup('pieces');
        let objects = pieces.getObjects();

        let node_pieces = this.node.getChildByName("lay_pieces");


        const clickEventHandler = new EventHandler();
        clickEventHandler.target = this.node; // 这个 node 节点是你的事件处理代码组件所属的节点
        clickEventHandler.component = 'LogicManager';// 这个是脚本类名
        clickEventHandler.handler = 'piecesOnClick';
        clickEventHandler.customEventData = '';

        let players: Array<Player> = this._parent.logicManager.currentGameState.players;
        let result: Array<Player> = players.filter((value: Player) => {
            return value.camp!=-1;
        });
        let camp = result[0].camp;
        // 绑定点击事件
        for(let i = 0;i<objects.length;i++) {
            let object = objects[i];

            let node = node_pieces.getChildByName(object.name);
            // 设置棋子
            let key = MapUtil.instance.getKey(node.position.x,node.position.y);
            MapUtil.instance.mapPieces.set(key,node);
            MapUtil.instance.mapObjPieces.set(object.name,object);


            // 0代表蓝方
            if(camp==0 && "b"===object.name.substr(0,1)){

                // 获取到精灵
                // let sprite = node.getComponent(Sprite);
                // resources.load("pieces/6/spriteFrame", SpriteFrame, (err, spriteFrame) => {
                //     sprite.spriteFrame = spriteFrame;
                // });


                const button= node.addComponent(Button);
                button.clickEvents.push(clickEventHandler);


                this._createFootPrint("up",node);
                this._createFootPrint("down",node);
                this._createFootPrint("left",node);
                this._createFootPrint("right",node);
                this._createAttackPrint("up",node);
                this._createAttackPrint("down",node);
                this._createAttackPrint("left",node);
                this._createAttackPrint("right",node);
            }

            // 1代表红方
            if(camp==1 && "r"===object.name.substr(0,1)){

                // 获取到精灵
                // let sprite = node.getComponent(Sprite);
                // resources.load("pieces/7/spriteFrame", SpriteFrame, (err, spriteFrame) => {
                //     sprite.spriteFrame = spriteFrame;
                // });


                const button= node.addComponent(Button);
                button.clickEvents.push(clickEventHandler);

                this._createFootPrint("up",node);
                this._createFootPrint("down",node);
                this._createFootPrint("left",node);
                this._createFootPrint("right",node);
                this._createAttackPrint("up",node);
                this._createAttackPrint("down",node);
                this._createAttackPrint("left",node);
                this._createAttackPrint("right",node);
            }

        }

        log(MapUtil.instance.mapPieces);
    }

    // 添加脚印
    private _createFootPrint(type:string,node:Node): Node {
        let footprint_node = new Node();
        footprint_node.name = type;

        // 设置层级
        footprint_node.layer = 33554432;
        // 设置锚点
        let ui = footprint_node.addComponent(UITransform);
        ui.setContentSize(148,148);
        ui.setAnchorPoint(0.5,0.5);


        // 添加事件
        const clickEventHandler = new EventHandler();
        clickEventHandler.target = this.node; // 这个 node 节点是你的事件处理代码组件所属的节点
        clickEventHandler.component = 'LogicManager';// 这个是脚本类名
        clickEventHandler.handler = 'onClickMove';
        clickEventHandler.customEventData = '';

        const button= footprint_node.addComponent(Button);
        button.clickEvents.push(clickEventHandler);

        footprint_node.active = false;
        footprint_node.parent = node;



        // 添加脚印图片
        let childNode = new Node();
        childNode.name = node.name+"_foot";
        childNode.parent = footprint_node;
        childNode.layer = footprint_node.layer;

        // 爪印
        let footprint = childNode.addComponent(Sprite);
        resources.load("pieces/foot/"+node.name+"/spriteFrame", SpriteFrame, (err, spriteFrame) => {
            footprint.spriteFrame =  spriteFrame;
        });
        // 设置锚点
        // let c_ui:UITransform = childNode.getComponent(UITransform) as UITransform;
        let c_ui:UITransform = childNode.addComponent(UITransform) as UITransform;
        c_ui.setContentSize(100,100);
        c_ui.setAnchorPoint(0.5,0.5);


        return footprint_node;
    }
    // 添加可攻击印记
    private _createAttackPrint(type:string,node:Node): Node{

        let footprint_node = new Node();
        footprint_node.name = "att_"+type;
        footprint_node.parent = this.node;
        // 爪印
        let footprint = footprint_node.addComponent(Sprite);
        resources.load("pieces/7/spriteFrame", SpriteFrame, (err, spriteFrame) => {
            footprint.spriteFrame =  spriteFrame;
        });
        // 设置层级
        footprint_node.layer = 33554432;
        // 设置锚点
        let ui = footprint_node.getComponent(UITransform);
        ui.setAnchorPoint(0.5,0.5);


        // 添加事件
        const clickEventHandler = new EventHandler();
        clickEventHandler.target = this.node; // 这个 node 节点是你的事件处理代码组件所属的节点
        clickEventHandler.component = 'LogicManager';// 这个是脚本类名
        clickEventHandler.handler = 'onClickFight';
        clickEventHandler.customEventData = '';

        const button= footprint_node.addComponent(Button);
        button.clickEvents.push(clickEventHandler);

        footprint_node.active = false;
        footprint_node.parent = node;

        return footprint_node;
    }


    /******* 陷阱、河道、兽穴 start **********/
    private initBlock(){
        // 陷阱
        let trap = this.node.getChildByName("trap").getComponent(TiledLayer);

        for (let i = 0; i < 7; i++) {
            for (let j = 0; j < 9; j++) {
                if(trap.getTileGIDAt(i, j)!=0){
                    let positionAt = trap.getPositionAt(i, j);
                    // 陷阱区分阵营
                    let camp = "blue";
                    if(positionAt.y > 666) camp = "red";
                    MapUtil.instance.mapTrap.set(MapUtil.instance.getTiledKey(this._posToTiled(positionAt.x,'x'),this._posToTiled(positionAt.y,'y')),camp);
                }
            }
        }

        // 兽穴 tiled 未指定 den
        // let childByName1 = this.tiledMap.getChildByName("lay_pieces");
        MapUtil.instance.mapBen.set(MapUtil.instance.getTiledKey(0,4),"red");
        MapUtil.instance.mapBen.set(MapUtil.instance.getTiledKey(0,-4),"blue");



        // 河道
        let river = this.node.getChildByName("block").getComponent(TiledLayer);

        for (let i = 0; i < 7; i++) {
            for (let j = 0; j < 9; j++) {
                if(river.getTileGIDAt(i, j)!=0){
                    let positionAt = river.getPositionAt(i, j);
                    MapUtil.instance.mapRiver.set(MapUtil.instance.getTiledKey(this._posToTiled(positionAt.x,'x'),this._posToTiled(positionAt.y,'y')),"");
                }
            }
        }
    }

    private _posToTiled(pos,index){
        if(index=='x'){
            return (pos - 444)/148;
        }else{
            return (pos - 740)/148;
        }
    }

    /******* 陷阱、河道、兽穴 end **********/
}

/**
 * [1] Class member could be defined like this.
 * [2] Use `property` decorator if your want the member to be serializable.
 * [3] Your initialization goes here.
 * [4] Your update function goes here.
 *
 * Learn more about scripting: https://docs.cocos.com/creator/3.3/manual/zh/scripting/
 * Learn more about CCClass: https://docs.cocos.com/creator/3.3/manual/zh/scripting/ccclass.html
 * Learn more about life-cycle callbacks: https://docs.cocos.com/creator/3.3/manual/zh/scripting/life-cycle-callbacks.html
 */
